<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="80%"
      append-to-body
      :before-close="close"
    >
      <el-row :gutter="10">
        <el-col :md="6" :sm="24">
          <!--          <div class="params-info">-->
          <!--            <el-table-->
          <!--              :data="-->
          <!--                textTable.filter(-->
          <!--                  (data) =>-->
          <!--                    !search ||-->
          <!--                    data.title.toLowerCase().includes(search.toLowerCase()) ||-->
          <!--                    data.explain.includes(search)-->
          <!--                )-->
          <!--              "-->
          <!--              ref="table"-->
          <!--            >-->
          <!--              <el-table-column label="占位符" align="center" prop="title">-->
          <!--                <template slot-scope="scope">-->
          <!--                  <div-->
          <!--                    style="-->
          <!--                      display: flex;-->
          <!--                      justify-content: space-between;-->
          <!--                      align-items: center;-->
          <!--                    "-->
          <!--                  >-->
          <!--                    <span>{{ scope.row.title }}</span>-->
          <!--                    <i-->
          <!--                      class="el-icon-document-copy"-->
          <!--                      v-clipboard:copy="scope.row.title"-->
          <!--                      v-clipboard:success="clipboardSuccess"-->
          <!--                      style="cursor: pointer; color: #3889f8"-->
          <!--                    ></i>-->
          <!--                  </div>-->
          <!--                </template>-->
          <!--              </el-table-column>-->
          <!--              <el-table-column label="说明" align="center" prop="explain" />-->
          <!--              <el-table-column label="举例" align="center" prop="ensample" />-->
          <!--            </el-table>-->
          <!--          </div>-->
          <div class="fieldBox">
            <el-row v-for="(item,index) in sortFieldList" :key="index" class="fieldBox__item"
                    :class="{'fieldBox__item--end':item.end}"
            >
              <el-col :span="18">
                {{ item.name }}
              </el-col>
              <el-col :span="6">
                <span v-clipboard:copy="'{'+item.name+'}'" v-clipboard:success="clipboardSuccess"
                      style="cursor: pointer; color: #3889f8"
                >复制</span>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col :md="18" :sm="24">
          <el-form ref="form" :model="form" :rules="rules">
            <el-form-item prop="templateContent">
              <editor v-model="form.templateContent" :savefile="false" :min-height="600"/>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listContractTemplateField,
  editContractTemplateContent
} from '@/api/contract/template'

import { debounce } from '@/utils'

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    title: {
      default: '编辑合同内容'
    },
    formData: {}
  },
  dicts: [],
  data() {
    return {
      visible: false,
      search: '',
      textTable: [
        {
          title: '${partyAName}',
          explain: '出租方(甲方)',
          ensample: '伊犁哈萨克自治州伊宁市物业公司'
        },
        {
          title: '${partyAContact}',
          explain: '甲方联系方式',
          ensample: '176****2318'
        },
        {
          title: '${partyBName}',
          explain: '承租方（乙方）',
          ensample: '张三'
        },
        {
          title: '${partyBContact}',
          explain: '乙方联系方式',
          ensample: '乙方联系方式	176****0919'
        },
        {
          title: '${partyBIdNumber}',
          explain: '乙方身份证',
          ensample: '5402011****9391'
        },
        {
          title: '${timeRange}',
          explain: '租赁期限',
          ensample: '2023-04-24 ~ 2024-04-24'
        },
        {
          title: '${rentStandard}',
          explain: '租金标准',
          ensample: ''
        },
        {
          title: '${deposit}',
          explain: '押金',
          ensample: '¥1000'
        },
        {
          title: '${address}',
          explain: '地址',
          ensample: 'xx省xx市xx区xx街道xx小区xx栋xx单元xx号'
        },
        {
          title: '${houseType}',
          explain: '户型',
          ensample: '两房一厅一卫'
        },
        {
          title: '${area}',
          explain: '面积',
          ensample: '80'
        },
        {
          title: '${day}',
          explain: '合同签订日期',
          ensample: '2023-4-24'
        }
      ],
      // 合同模板字段列表
      fieldList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  computed: {
    sortFiled: {
      get() {
        let sort1 = []
        let sort2 = []
        let sort3 = []
        switch (this.formData.templateType) {
          case '1':
            sort1 = ['${contractId}', '${tenantName}', '${tenantPhone}', '${tenantIdCard}']
            sort2 = ['${city}', '${houseAddress}', '${houseType}', '${floor}', '${totalFloor}', '${houseArea}', '${startDate}', '${endDate}', '${payType}']
            sort3 = ['${paymentMethod}', '${rentAmount}', '${depositAmount}', '${rentDay}', '${signer}', '${signDate}', '${additionalTerms}', '${houseFacilities}', '${electricityMeterReading}', '${waterMeterReading}']
            // return [...sort1, ...sort2, ...sort3]
            return {
              list: [...sort1, ...sort2, ...sort3],
              sort: [sort1.length, sort1.length + sort2.length, sort1.length + sort2.length + sort3.length]
            }
          case '2':
            sort1 = ['${contractId}', '${companyName}', '${creditCode}', '${contactPerson}', '${contactPhone}', '${city}', '${houseAddress}', '${houseType}', '${floor}', '${totalFloor}', '${houseArea}', '${startDate}', '${endDate}', '${payType}']
            sort2 = ['${paymentMethod}', '${rentAmount}', '${depositAmount}', '${rentDay}', '${signer}', '${signDate}', '${additionalTerms}', '${houseFacilities}', '${electricityMeterReading}', '${waterMeterReading}']
            return {
              list: [...sort1, ...sort2],
              sort: [sort1.length, sort1.length + sort2.length]
            }
          case '3':
            sort1 = ['${contractId}', '${city}', '${houseAddress}', '${houseType}', '${floor}', '${totalFloor}', '${houseArea}', '${startDate}', '${endDate}', '${rentAmount}', '${depositAmount}']

            sort2 = ['${accountHolder}', '${bankAccount}', '${bankName}', '${bankBranch}']
            return {
              list: [...sort1, ...sort2],
              sort: [sort1.length, sort1.length + sort2.length]
            }
          case '4':
            sort1 = ['${contractId}', '${city}', '${houseAddress}', '${houseType}', '${floor}', '${totalFloor}', '${houseArea}']
            sort2 = ['${servicePeriod}', '${preparationPeriod}', '${billingServiceFee}']
            sort3 = ['${accountHolder}', '${bankAccount}', '${bankName}', '${bankBranch}']
            return {
              list: [...sort1, ...sort2, ...sort3],
              sort: [sort1.length, sort1.length + sort2.length, sort1.length + sort2.length + sort3.length]
            }
          default:
            return ''
        }
      },
      set(val) {

      }

    },
    sortFieldList: {
      get() {
        let list = []
        this.fieldList.map(item => {
          let index = this.sortFiled.list && this.sortFiled.list.findIndex(value => value === item.fieldName)
          if (index >= 0) {
            item['sort'] = index
          } else {
            item['sort'] = 999999
          }

          if (this.sortFiled.sort && this.sortFiled.sort.includes(index + 1)) {
            item['end'] = true
          }
          list.push(item)
        })
        return list.sort((a, b) => {
          return a.sort - b.sort
        })
      },
      set(val) {
      }

    }
  },
  watch: {
    value(newVal, oldVal) {
      this.visible = newVal // 监测value的变化，并赋值。
      if (newVal) {
        this.form = this.formData
        this.init()
      }
    },
    visible(val) {
      this.$emit('input', val) // 此处监测showMask目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
    }
  },
  methods: {
    init() {
      this.listContractTemplateField()
    },
    //重置表单
    reset() {
      // this.form = {
      //   templateContent: '', //合同模板内容
      // }
      this.resetForm('form')
    },
    listContractTemplateField() {
      let params = {
        fieldType: this.formData.templateType
      }
      listContractTemplateField(params).then((response) => {
        this.fieldList = response.data
      })
    },
    /** 提交按钮 */
    submitForm: debounce(function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          editContractTemplateContent(this.form).then((response) => {
            this.$modal.msgSuccess(response.msg)
            this.$emit('success')
          })
          this.close()
        }
      })
    }, 500),
    // 取消按钮
    cancel() {
      this.reset()
      this.visible = false
    },
    close() {
      this.reset()
      this.visible = false
    },
    /** 复制代码成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess('复制成功')
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}

.params-info {
  max-height: 70vh;
  overflow-y: auto;

  .title {
    margin-bottom: 20px;

    label {
      font-size: 16px;
    }

    .prompt {
      padding: 5px 0;
      color: #fcc17f;
    }
  }

  .search {
    margin-bottom: 10px;
  }
}

.fieldBox {
  background: #F2F2F2;
  padding: 20px;

  .fieldBox__item {
    margin-bottom: 10px;

    &.fieldBox__item--end {
      margin-bottom: 30px;
    }
  }
}
</style>
